<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" type="primary" size="mini" @click="handleShowDialog">
      上传
    </el-button>
    <!-- 图片列表 -->
    <ul v-if="showList" style="marginTop:20px;display:block;" class="el-upload-list el-upload-list--picture-card">
      <div>
        <li tabindex="0" v-for="(item,i) in defaultList" :key="i" class="el-upload-list__item is-success">
          <img :src="item.url" class="el-upload-list__item-thumbnail">
          <!-- <el-image style="width:20%" class="el-upload-list__item-thumbnail" :src="item.url" :preview-src-list="[item.url]"></el-image> -->
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-delete">
              <i @click="handleMoveFileList(i)" class="el-icon-delete"></i>
              <i @click="handlePrev($event,item)" class="el-icon-search"></i>
            </span>
          </span>
        </li>
      </div>
    </ul>
    <!-- 这里希望有一个预览列表 -->
    <el-dialog :visible.sync="prev" :append-to-body='true'>
      <img width="100%" :src="prevUrl" alt="">
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" :append-to-body='true' :destroy-on-close="true">
      <el-upload
        :limit="limit"
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :on-exceed="handleExceed"
        class="editor-slide-upload"
        :action="UploadFileUrl"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          点击上传
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'

export default {
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    showList: {
      type: Boolean,
      default: true
    },
    limit: {
      type: Number,
      default: 1
    },
    // 外面预览的时候的列表
    defaultList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const UploadFileUrl = this.$api.UploadFileUrl

    // debugger
    return {
      dialogVisible: false,
      listObj: {},
      fileList: [], // dialog里的列表
      UploadFileUrl,
      prev: false,
      prevUrl: '' // 内部预览的图片地址
      // defaultList: defaultList // 外面预览的时候的列表
    }
  },

  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message('请等待所有图片上传完毕，如果遇到网络问题，请刷新页面重新尝试！')
        return
      }
      this.$emit('successCBK', arr)
      this.listObj = {}
      this.fileList = []
      Array.isArray(arr) && this.defaultList.push(...arr)
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = response.data
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    beforeUpload(file) {
      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function() {
          _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
        }
        resolve(true)
      })
    },
    handleMoveFileList(i) {
      this.defaultList.splice(i, 1)
      this.$emit('delCallBack', this.defaultList)
    },
    handleExceed() {
      this.$message({
        type: 'warning',
        message: `最多可以上传${this.limit}张图片`
      })
    },
    // 显示隐藏上传文件框
    handleShowDialog() {
      // const { defaultList } = this.$data
      if (this.defaultList.length >= this.limit) {
        this.$message({
          type: 'warning',
          message: `最多可以上传${this.limit}张图片哦`
        })
        return
      }
      this.dialogVisible = true
    },
    // 移除外面预览的时候的列表
    RemovePrevFileList() {
      // this.defaultList = []
    },
    // 内部预览的
    handlePrev(e, { url }) {
      this.prev = true
      this.prevUrl = url
    }
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
</style>
